package com.gxljc.bear.crawler.weixin;

import com.gxljc.commons.util.AdvFile;
import com.gxljc.commons.util.ILineParser;
import com.gxljc.commons.util.Pair;
import com.gxljc.commons.util.StringUtil;
import com.gxljc.bear.crawler.base.DolphinCrawlerConf;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 新榜微信账号数据爬虫。
 *
 * @author tanghaitao
 * @since 2022-10-18
 */
public class NewRankNonceInfo implements Serializable {
    public static Logger LOG = Logger.getLogger(NewRankNonceInfo.class);
    private Map<String, NonceInfoObj> map = new HashMap<String, NonceInfoObj>();

    private static final NewRankNonceInfo info = new NewRankNonceInfo();

    private NewRankNonceInfo() {
        try {
            init();
        } catch (Exception er) {
            er.printStackTrace();
        }

    }

    public String getUrl(AccountTable table) {
        String id = table.accountId;
        NonceInfoObj obj = map.get(id);
        String uuid = table.uuid;
        String nonce = "";
        String xgxljc = "";
        String flag = "";
        if (obj != null) {
            nonce = obj.nonce;
            xgxljc = obj.xgxljc;
            flag = obj.flag;
        }
        return String.format(WeixinConst.NEWRANK_PAGE_URL, uuid, nonce, xgxljc, flag);
    }

    public static NewRankNonceInfo getInstance() {
        return info;
    }

    private void init() throws Exception {
        final String filename = "weixin_newrank_nonce.txt";
        Configuration conf = DolphinCrawlerConf.getInstance();
        AdvFile.loadFileInDelimitLine(
                conf.getConfResourceAsInputStream(filename), new ILineParser() {
                    @Override
                    public void parseLine(String line) {
                        String[] split = line.split(StringUtil.STR_DELIMIT_3RD);
                        if (split.length != 4) {
                            return;
                        }
                        String word1 = split[0].trim();
                        String word2 = split[1].trim();
                        String word3 = split[2].trim();
                        String word4 = split[3].trim();

                        NonceInfoObj obj = new NonceInfoObj();
                        obj.setId(word1);
                        obj.setNonce(word2);
                        obj.setXgxljc(word3);
                        obj.setFlag(word4);

                        if (word1.isEmpty() || word2.isEmpty() || word3.isEmpty() || word4.isEmpty()) {
                            return;
                        }
                        map.put(word1, obj);
                    }
                });
    }
}
